
function fn_void(){return true;} //do nothing!

function getbyid(id){return document.getElementById(id);}

/**
  显示警告的方式
  */
function show_alert(msg){
	alert(msg);
}

/**
显示一个对话框
arg(object):
  id	对话框的id
  title	显示用的标题
  height&width	宽高
  content	显示的内容HTML格式，不需要<html><body>等
  buttons	对话框的按钮，参见jq.ui.dialog的详细说明
			若不指定使用默认按钮和形为，见源码
  click		点击“确定”后的处理函数，优先于ajaxform
  ajaxform	若提供使用ajaxform約束content的form形为，詳见ajax_form()
  */
function show_dialog(arg)
{
	var id = arg.id ? arg.id : 'dialog1';
	var title = arg.title ? arg.title : 'Untitled';
	var height = arg.height ? arg.height : 350;
	var width = arg.width ? arg.width : 350;
	var content = arg.content ? arg.content : '';
	var fn_click = arg.click ? arg.click : fn_void;

	var html = '<div id="'+id+'" title="'+title+'" class="">'+content+'</div>';
	var buttons = arg.buttons ? arg.buttons : ({
			'取消': function() {$(this).dialog('close');},
			'确定': function() {
				if(!fn_click()){return;}
				var formid = $('#'+id).attr('formid'); //From ajaxform.id
				if(formid){$("#"+formid).submit();} //ajaxform负责关闭dialog
				else{$(this).dialog('close');}
			}
		});

	$('#'+id).remove();  //Remove previous dialog 
	$('body').append(html);

	if(arg.ajaxform){
		if(typeof arg.ajaxform == 'function'){ //success function only
			var func = arg.ajaxform;
			arg.ajaxform = {success : func};
		}
		if(!arg.ajaxform.id){
			arg.ajaxform.id = $('#'+id+' > form').attr('id');
		}
		$('#'+id).attr('formid', arg.ajaxform.id); //let dialog know form`id
		arg.ajaxform.dialog = id; //assign dialog id
		ajax_form(arg.ajaxform);
	}

	$("#"+id).dialog({
		bgiframe:	1,
		resizable:	1,
		autoOpen:	0,
		height:		height,
		width:		width,
		modal:		1,
		buttons:	buttons
	});

	$('#'+id).dialog('open');
}

function close_dialog(arg)
{
	var id = arg.id ? arg.id : 'dialog1';
	$('#'+id).dialog('close');
}

/**
Ajax form初始化函数FORM必需有ID属性存在
arg(object):
  id	formid
  dialog	form提交完成后，自动关闭dialog；在dialog里指定ajaxform时自动加此参数
  before	ajaxform.beforeSubmit()
  finish	ajaxform.success()，指从服务器返回数据后
  success	ajaxform.success()后，判断返回状态，为成功时执行
  failure	ajaxform.success()后，判断返回状态，为失败时执行
  */
function ajax_form(arg)
{
	if(typeof arg == 'function'){ //success function only
		var func = arg;
		arg = {success : func};
	}
	else if(!arg){
		arg = {};
	}

	var id = arg.id ? arg.id : 'form1';
	var dialog = arg.dialog ? arg.dialog : null;

	var fn_before = arg.before ? arg.before : fn_void;

	var fn_finish = arg.finish ? arg.finish : function(jsn){
			show_alert(jsn.message);
			if(ajax_ok(jsn)){
				fn_success(jsn);
				if(jsn.jump){location.href=jsn.jump;}
			}
			else{
				fn_failure(jsn);
			}
		};
	var fn_success = function(jsn){
			(arg.success ? arg.success : fn_void)(jsn);
			if(arg.reset) $("#"+id).get(0).reset();
			if(dialog) close_dialog({id:dialog});
		};
	var fn_failure = arg.failure ? arg.failure : fn_void;

	$("#"+id).ajaxForm({
		'beforeSubmit' : fn_before,
		'success' :	fn_finish
	});
}

/**
  判断服务器返回是否成功结果
  */
function ajax_ok(jsn){
	return (-1!=('|note|ok|notice|'.indexOf('|'+jsn.level+'|'))) ? true: false;
}

//验证输入文字为整形
function chkdig_int(obj) {
	if(! $(obj).attr('_chkdig_init')) {
		var a = function(){chkdig_int(obj);};
		//$(obj).mouseover(a);
		//$(obj).keydown(a);
		//$(obj).keyup(a);
		$(obj).blur(a);
		$(obj).focus(a);
		$(obj).attr('_chkdig_init', true);
	}
	var t=1* obj.value.replace(/[^\d\-]+/,'');
	obj.value=t?t:'';
}

function chkdig_float(obj, scale) {
	if(!scale) scale=2;
	if(! $(obj).attr('_chkdig_float')) {
		var a = function(){chkdig_float(obj, scale);};
		//$(obj).mouseover(a);
		//$(obj).keydown(a);
		//$(obj).keyup(a);
		$(obj).blur(a);
		$(obj).focus(a);
		$(obj).attr('_chkdig_float', true);
	}
	var t=(1 * obj.value.replace(/[^\d\.\-]+/,''));
	obj.value= t?t.toFixed(scale):'';
}

//切换菜单显示
//param1:菜单数字ID， param2:高亮的子ID， param3:显示动画秒数
function switch_menu(mid)
{
	if(!mid) return;
	var submid=0, sec=200;
	if(arguments.length>1) {
		submid = arguments[1];
		if(arguments.length>2)
			sec = arguments[2];
	}
	if($("#submenu_"+mid).attr("inshow")==1) {
		$("#submenu_"+mid).attr("inshow", 0);
		if(sec) $("#submenu_"+mid).hide(sec); else $("#submenu_"+mid).hide();
	}
	else {
		$("#submenu_"+mid).attr("inshow", 1);
		if(sec) $("#submenu_"+mid).show(sec); else $("#submenu_"+mid).show();
	}
}

//输入回车进行搜索（避免在input里自动提交），并指定自定义的回车接收事件
function register_search_key(id, func) {
	$("#"+id).keydown(function(e){
		if(e.which==13){
			if(func) setTimeout(func, 100);
			return false;
		}
	});
}

//记录开启菜单ID
function archor(aid) {
	$.cookie('_archor_', aid, {path:'/',secure:false});
}

//"返回"的功能
function gback(url) {
	if(url) location.href = url;
	else history.back(-1);
}

function g2(url) {
	location.href = url;
}

//返回SELECT被选中的option的text
function soptxt(id) {
	return $('#'+id+' option[value='+$('#'+id).val()+']').text();
}

function sw_choose_on(){
	$("#sw_wareid").attr('disabled', false);
	$("#sw_choose").attr('disabled', false);
}
function sw_choose_off(){
	$("#sw_wareid").attr('disabled', true);
	$("#sw_choose").attr('disabled', true);
	$("#sw_wareid").html('');
}
function sw_init(){
	if($('#sw_key').val()) sw_search_stuff();
	register_search_key('sw_key', sw_search_stuff);
	$("#sw_key").change(sw_choose_off);
}
var L_stuff = new Array();
//检索材料信息
function sw_search_stuff()
{
	var v = $('#sw_key').val();
	if(v.length<1) {
		show_alert("请输入至少一个字符的检索条件.");
		return;
	}
	$('#sw_wareid').empty();
	$.post(URL_SRCHSTUFF, {"v":v}, function(jsn){
		if(!ajax_ok(jsn)){
			show_alert(jsn.message);
		}
		else if(jsn.wares.length>0){
			sw_choose_on();
			$('#sw_key').blur();
			$('#sw_wareid').append('<option value="">--检索结果--</option>');
			html = '';
			$.each(jsn.wares, function(i,o){
				html += ('<option value="'+o['id']+'">'+o['sno']+' | '+o['name']+' | '+o['brand']+' | '+o['specific']+'</option>');
				L_stuff[o['id']] = o;
			});
			$('#sw_wareid').append(html);
			$('#sw_wareid').focus();
		}
		else{
			$('#sw_wareid').append('<option value="">--无结果--</option>');
		}
	});
}

function sw_add_stuff(type)
{
	var stuff_id = $('#sw_wareid').val();
	if(!stuff_id) return ;

	if(getbyid('selstf_'+stuff_id)) {
		show_alert("请勿重复选择同型号材料.");
		return;
	}

	$.get(URL_WARECHOOSE.replace('ID', stuff_id).replace('TYPE', type), function(html){
		$('#stuff_list > tbody').append(html);
		do_stuff_total();
	});
}

//计算材料总价
function do_stuff_total()
{
	var total = 0;
	$('#stuff_list input').each(function(i,o){
		total += (o.value* $(o).attr('stfprc'));
	});
	total = Math.round(total*100)/100;
	$('#stuff_fund').html("总价："+total);
}

//计算材料总价
function do_stuff_total2()
{
	var total = 0;
	$('#stuff_list input[name^=amount]').each(function(i,o){
		total += (o.value* $('[name='+$(o).attr('pcname')+']').val());
	});
	total = Math.round(total*100)/100;
	$('#stuff_total').val(total.toFixed(2));
}

//检查用记输入采购数量
function check_amount(){
	var flag = true;
	$('input[name^=amount]').each(function(){with($(this)){
		focus();
		if(!val()) {
			flag = false;
			parent().css('background-color', 'red');
		}
		else{
			parent().css('background-color', '');
		}
	}});
	if(!flag){
		show_alert('请输入标红格背景的采购数量');
	}
        return flag;
}

//分页
function pager(baseurl){
	var pager_roll_num = 1;
	var aa = function(){
		pager_roll_num = $(this).html();
		$(this).replaceWith("<input type='text' class='decimal' size='2' onfocus='chkdig_int(this)' id='pgroll' value='"+$(this).html()+"' /> ");
		with($('#pgroll')){
			focus();select();
			register_search_key('pgroll', function(){g2(baseurl.replace('{PAGE}', val()));});
			blur(function(){
				replaceWith("<span class='pointer underline' id='pgroll'> "+pager_roll_num+" </span>");
				$('#pgroll').click(aa);
			});
		}
	};
	$("#pgroll").click(aa);
}


/**  级联选择材料分类信息，调用方法: $('#xxx').change(rec_stuffcls);  */
function rec_stuffcls()
{
	var _id	= this.id+'_';
	$('select[id^='+_id+']').remove(); //Drop children first.

	//show selected stuff code.
	code	= $(this).find('option:selected').attr('code');
	$('#precode').html(code?code+'-':'');

	if(!$(this).val()) return;
	_get_stuffcls(this, this.id+'_'+$(this).val());
}
function _get_stuffcls(_old, _n_id, _vals)
{
	$.get(URL_REC_STUFFCLS.replace('ID',$(_old).val()),function(jsn){
		try{
			if(jsn.items) {
				$(_old).after('<select name="'+$(_old).attr('name')+'" id="'+_n_id+'"><option value=""></option></select>');
				var obj	=	document.getElementById(_n_id);
				$(obj).change(rec_stuffcls);
				$.each(jsn.items, function(i,o){
					$(obj).append('<option value="'+o.id+'" code="'+o.code+'">'+o.title+'</option>');
				});
				//递归显示后续材料分类(select)
				if(""!=_vals && _vals.length>0)
				{
					var vv	= _vals.shift();
					$(obj).val(vv);
					_get_stuffcls(obj, _n_id+'_'+vv, _vals);
				}
			}
		}catch(e){}
	});
}
/** 生成用于级联材料分类的根 */
function root_stuffcls(tname, tid, path)
{
	document.write("<span name='"+tname+"' id='"+tid+"'></span>");
	_get_stuffcls($('#'+tid), tid+'_R', path.substr(1,path.length-2).split('/'));
}

function round(value){
//	return Math.round(100*value)/100;
	if(value){
		return (o=parseFloat(value)) ? o.toFixed(2) : '0.00';
	}
};
function resize_fnum(){
	var i=0;
	$('.fnum').each(function(){
		if(this.getAttribute('_fnc')) return ;
		if(this.innerHTML){
			this.innerHTML = round(this.innerHTML);
		}
		if(this.value){
			this.value = round(this.value);
		}
		this.setAttribute('_fnc', 1);
		i++;
	});
//	console.debug(i);
}


//打印分页加头和尾
function resetPrintPage()
{
    //检查表的高度 
       if($('#printArea').length==0){ return null;}
       //打印换成像素: 打印边距为0mm时794x1123 为5mm时756x1086 为19.05mm时649x978 默认选择一个最小值
       var limitedH = 980; 
       if($.browser.msie) limitedH = 972;
       if($('#printArea').attr('class')=="horizontal"){ //横向打印
           $('#printArea').css('width',limitedH+'px');
           limitedH = 643;           
       } 
       
       
       if($('#printArea').height()>limitedH)
       {
          var t = $('.ptop').height(); 
          var ct = $('.pcontent thead').height();
          var b = $('.pbot').height();          
          
          var ih = limitedH - (t + ct + b); //中间表最大高度   
          var _frame = $('#printArea').clone(); //框架
          _frame.find('.pcontent tbody').empty();//删除表内容，稍后重建 
          
          var frame = _frame.html();         

          function itemscombine(x)
           {            
                 var items =  $('#printArea >.pcontent>tbody>tr');
                 var itemh = 0;
                 $('#printArea').append("<div id=\"items_"+x+"\" style=\"height:"+limitedH+"px;\">"+frame+"<\/div>");
                 items.each(function(n,i){
                      if(itemh+$(i).height() < ih)
                      {
                          itemh += $(i).height();
                          //$('#items_'+x+'>.pcontent>tbody').append('<tr height=\"'+($(i).height()-1)+'\">'+$(i).html()+'<\/tr>');
                          $('#items_'+x+'>.pcontent>tbody').append('<tr>'+$(i).html()+'<\/tr>');
                           $('#items_'+x+'>.pcontent').attr('height',limitedH);
                          items.eq(n).remove(); //删除                      
                      }
                      else
                      {
                           return false;
                      }
                  }); 
                  
              $('#items_'+x+'>.pcontent').attr('height',ct+itemh);
              if($('#printArea >.pcontent tbody tr').length>0)
             {
                itemscombine(x+1); 
              }
              else
              {
                $('#printArea >.ptop,#printArea >.pcontent,#printArea >.pbot').remove(); //清空
              }
           }   
           
           function _itemscombine(x)
           {
               itemscombine(x);
           }

          itemscombine(0); 
       }
}

//关闭单条feedback显示
function closefeedback(id,obj)
{
    $.get('/proc-closefeedback/id/'+id,{},function(res){
        if('true'==res.isOK)
        {
           window.location.reload();
        }
        else
        {
           alert('操作失败！');
        }
    },'json');
}